package com.ccx.coachsite.service;

import com.ccx.coachsite.ui.login.LoginHelper;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.text.format.Time;

/**
 * 定时轮询服务器查询是否有分享记录
 * @author cfb
 *
 */
public class ShareMessageService extends Service {

	/**一分钟*/
	public final static int ONE_MINUTE = 10000;//20秒检测一次
	/**下次更新间隔时间序号*/
	public static int indexTime = 0;
	public int[] indexArray = {1,1,1,2,2,2,1,2};
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		
		//判断是否登录,如果未登录则不检查。
		if ( !LoginHelper.isLogin(this) )
			return ;
		
		//执行检查服务
		GetShareMessageTask task = new GetShareMessageTask(this);
		task.execute();
		
		// 执行检查未读留言
		ReceiveMessageTask receiveMessageTask = new ReceiveMessageTask(this);
		receiveMessageTask.execute(0);
		
		//SystemMessageTask systemMessageTask = new SystemMessageTask(this);
		//systemMessageTask.execute(0);
		
		//设置下次定时请求
		long updateTime = ONE_MINUTE * indexArray[indexTime];
		indexTime = (indexTime+1)%indexArray.length;
		Intent updateIntent=new Intent();   
        updateIntent.setClass(this, ShareMessageService.class);   
        PendingIntent pending=PendingIntent.getService(this, 0, updateIntent, 0); 
        
		Time time = new Time();   
        long nowMillis = System.currentTimeMillis();
        time.set(nowMillis + updateTime);
        long updateTimes = time.toMillis(true);
        AlarmManager alarm=(AlarmManager)getSystemService(Context.ALARM_SERVICE);   
        alarm.set(AlarmManager.RTC_WAKEUP, updateTimes, pending);
        
        stopSelf();
	}
}
